﻿using System;
using Microsoft.SharePoint;

namespace RealDolmen.SharePoint.Helpers
{
    public class SPWorkItemHelper
    {
        public static void CreateWorkItem(SPListItem listItem, Guid workItemType, DateTime scheduledDate)
        {
            CreateWorkItem(listItem, workItemType, scheduledDate, string.Empty);
        }

        public static void CreateWorkItem(SPListItem listItem, Guid workItemType, DateTime scheduledDate, string textPayLoad)
        {
            string weburl = string.Empty;
            Guid webid = Guid.Empty;

            using (SPWeb web = listItem.Web)
            {
                weburl = web.Url;
                webid = web.ID;
            }


            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(weburl))
                {
                    site.AddWorkItem(Guid.Empty, scheduledDate.ToUniversalTime(), workItemType,
                        webid, listItem.ParentList.ID, listItem.ID,
                        false, listItem.UniqueId, Guid.Empty, site.SystemAccount.ID, null, textPayLoad, Guid.Empty);
                }
            });
        }

        public static SPListItem GetListItem(SPWorkItem workitem)
        {
            SPListItem listItem;

            using (SPSite site = new SPSite(workitem.SiteId))
            {
                using (SPWeb web = site.OpenWeb(workitem.WebId))
                {
                    SPFile file = web.GetFile(workitem.ItemGuid);
                    listItem = web.GetListItem(file.ServerRelativeUrl);
                }
            }

            return listItem;
        }

        public static SPWorkItemCollection GetSubCollectionFor(SPWorkItemCollection workItems, SPListItem listItem)
        {
            using (SPWeb web = listItem.Web)
            {
                using (SPSite site = web.Site)
                {
                    return workItems.SubCollection(site, web, 0, (uint)workItems.Count);
                }
            }
        }
    }

}
